<?php

namespace app\modules\admin\models;

use Yii;

/**
 * This is the model class for table "cms_post_extend_text".
 *
 * @property int $id 自增主键
 * @property string $post_id 文档id
 * @property string $field 扩展字段名
 * @property string $value 扩展字段内容
 * @property int $deleted 0 未删除 1已删除
 * @property string $created 创建时间
 * @property string $modified 修改时间
 */
class CmsPostExtendText extends BaseModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'cms_post_extend_text';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['post_id', 'field'], 'required'],
            [['value'], 'string'],
            [['deleted'], 'integer'],
            [['created', 'modified'], 'safe'],
            [['post_id'], 'string', 'max' => 20],
            [['field'], 'string', 'max' => 30],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', '自增主键'),
            'post_id' => Yii::t('app', '文档id'),
            'field' => Yii::t('app', '扩展字段名'),
            'value' => Yii::t('app', '扩展字段内容'),
            'deleted' => Yii::t('app', '0 未删除 1已删除'),
            'created' => Yii::t('app', '创建时间'),
            'modified' => Yii::t('app', '修改时间'),
        ];
    }

    /**
     * 添加记录
     * @access public
     * @author furong
     * @param $data
     * @return bool|mixed
     * @since 2017年7月28日 09:37:59
     * @abstract
     * @throws \Exception
     */
    public function addRecord($data)
    {
        $data['modified'] = getDateTime();
        $return = false;
        $orm = $this->orm();
        $obj = $orm->andWhere(['post_id' => $data['post_id']])
            ->andWhere(['field' => $data['field']])
            ->one();
        if (!$obj) {
            #添加
            $data['created'] = $data['modified'];
            $this->setAttributes($data);
            if (!$return) {
                $this->setMessage('插入记录失败');
            }
            $id = \Yii::$app->db->getLastInsertID();
        } else {
            $id = $obj->id;
            $obj->setAttributes($data);
            #修改
            $return = $obj->update();
        }
        return $return ? $id : $return;
    }
}
